<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/6/11
 * Time: 10:38
 */
namespace App\Services;

use App\Logic\ToolLogic;
use App\Model\FriendModel;
use App\Model\GroupModel;
use App\Model\MsgModel;
use App\Model\UserModel;
use EasySwoole\EasySwoole\Config;



/**聊天业务
 * Class ChatService
 * @package App\Services
 */
class ChatService
{

    /**
     * 同步最后一条消息
     */
    public function syncLastMsg($param,$userInfo){
        try{
            $host = Config::getInstance()->getConf('APP.FILE_DOMAIN');
            $list = $param['extra']['condition'];
            foreach ($list as &$val){
                #单聊
                if($val['type']==1){
                    $friendUserInfo = UserModel::create()->get(['app_user_id'=>$val['id'],'app_id'=>$userInfo['app_id']]);
                    if(empty(  $friendUserInfo)){
                        continue;
                    }
                    $friendInfo = FriendModel::create()->get(['user_id'=>$userInfo['id'],'friend_user_id'=>$friendUserInfo['id']]);
                    if(empty( $friendInfo)){
                        continue;
                    }
                    $lastMsg =MsgModel::create()->order('id')->get(['unionid'=>$friendInfo['unionid']]);
                    if(empty( $lastMsg)){
                       echo 'empty'.PHP_EOL;
                        $val['last_message'] = null;
                        continue;
                    }
                   echo '同步消息，消息非空';
                    #接收人信息
                    #接收人是自己
                    if($lastMsg['to_id']==$userInfo['id']){
                        $senderInfo   = $friendUserInfo;
                        $receiverInfo =  $userInfo;
                    }else{//接收人是好友
                        $senderInfo   =  $userInfo;
                        $receiverInfo =  $friendUserInfo;
                    }
                    $friend['app_user_id'] =  $senderInfo['app_user_id'];
                    $friend['nickname'] = $senderInfo['nickname'];
                    $friend['head'] = $senderInfo['head'];
                    $data = array(
                        'to_user_id' =>$lastMsg['to_id'],
                        'app_user_id'=>$senderInfo['app_user_id'],
                        'to_app_user_id'=>$receiverInfo['app_user_id'],
                        'user_id'=>$senderInfo['id'],
                        'content'=>$lastMsg['msg'],
                        'nickname'=>$senderInfo['nickname'],
                        'head'=>$senderInfo['head'],
                        'type'=>$lastMsg['type'],
                        'extra'=>$lastMsg['extra']
                    );
                    #文件处理
                    switch ($lastMsg['type']){
                        default:
                            $data['extra'] = json_decode($data['extra'],true);
                    }
                    $messageArr = array(
                        'code'=>ReponseCodeService::CODE_OK,
                        'msg'=>"发送成功",
                        'data'=>json_encode($data,JSON_FORCE_OBJECT),
                        'action'=>'chat',
                        'nonce'=>$lastMsg['nonce'],
                        'time'=>HelpService::strDateToMsectime($lastMsg['created_at']),
                        'user_id'=>$userInfo['id'],
                        'msg_id'=>$lastMsg['id'],
                    );
                    $val['last_message'] =  $messageArr;
                }else{#群聊
                    $lastGroupMsg =  MsgModel::create()->order('id')->get(['to_id'=>$val['id']]);
                    if(empty($lastGroupMsg)){
                        $val['last_message'] = null;
                        continue;
                    }
                    $msgSender = UserModel::create()->get(['id'=>$lastGroupMsg['user_id']]);
                    if(empty( $msgSender)){
                        continue;
                    }
                    $data = array(
                        'group_id' =>$val['id'],
                        'content'=>$lastGroupMsg['msg'],
                        'type'=>$lastGroupMsg['type'],
                        'extra'=>$lastGroupMsg['extra'],
                        'app_user_id'=>$msgSender['app_user_id'],
                        'nickname'=>$msgSender['nickname'],
                        'head'=>$msgSender['head'],
                    );
                    $data['service_msg'] = false;
                    $groupInfo = GroupModel::create()->get(['id'=>$val['id']]);
                    if($groupInfo['service_user_id']!=0){
                        $data['service_msg'] = true;
                    }
                    #群不存在
                    if($groupInfo['status']!=GroupModel::STATUS_NORMAL){
                        continue;
                    }
                    #文件处理
                    switch ( $lastGroupMsg['type']){
                        default:
                            $data['extra'] = json_decode($data['extra'],true);
                    }

                    $messageArr = array(
                        'code'=>ReponseCodeService::CODE_OK,
                        'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
                        'data'=>json_encode($data),
                        'action'=>'groupChat',
                        'nonce'=>$param['nonce'],
                        'time'=>HelpService::strDateToMsectime($lastGroupMsg['created_at']),
                        'msg_id'=>$lastGroupMsg['id'] ,
                        'group_id' =>$lastGroupMsg['group_id'],
                    );
                    $val['last_message'] = $messageArr;
                }
            }
            return $list;
        }catch(\Throwable $t){
            echo $t->getMessage();
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }


    /**切换客服
     * @param $param
     * @param $userInfo
     */
    public function switchService($param, $userInfo){
        try{
            $appUserId = $param['extra']['app_user_id'];
            $groupId = $param['group_id']['group_id'];
            #获取客服信息
            $serviceInfo = UserModel::create()->get(['app_user_id'=>$appUserId,'app_id'=>$userInfo['app_id'],'type'=>UserModel::USER_TYPE_SERVICE]);
            #用户不存在
            if(empty($serviceInfo )){
                return ReponseCodeService::CODE_USER_NOT_FUND;
            }
            #修改绑定客服
            if(GroupModel::create()->update(['service_user_id'=>$serviceInfo['id']],['id'=>$groupId])){
                #给客户端发消息
                $groupMessage = array(
                    'extra' => array(),
                    'type'=>MsgModel::MSG_TYPE_TEXT,
                    'group_id'=> $groupId,
                    'content'=>"您好，{$serviceInfo['nickname']}为您服务。",
                );
                $msgService = new MsgService();
                $msgService->groupChat( $groupMessage, $serviceInfo);
                return ReponseCodeService::CODE_OK;
            }
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;

            }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }




    /**
     * 同步群聊消息
     */
    protected function syncGroupMessage($userId){

    }

    /**
     * 同步系统消息
     */
    protected function syncSystemMessage($userId){

    }
}